package com.example.musicaiap.ui.playlist

import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.outlined.Favorite
import androidx.compose.material.icons.outlined.FavoriteBorder
import androidx.compose.material.icons.outlined.MoreVert
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.blur
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.zIndex
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.example.musicaiap.domain.model.Playlist
import com.example.musicaiap.domain.model.Song
import com.example.musicaiap.mvi.base.CollectState
import com.example.musicaiap.ui.components.MiniPlayer
import com.example.musicaiap.ui.components.PlaylistBottomSheet
import com.example.musicaiap.ui.theme.QQGreen
import com.example.musicaiap.ui.theme.QQPlaylistBackground
import com.example.musicaiap.ui.theme.QQTagBackground
import com.example.musicaiap.ui.theme.QQVipBackground
import com.example.musicaiap.ui.theme.QQVipText
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import com.example.musicaiap.navigation.NavigationState
import com.example.musicaiap.service.PlaybackState
import com.example.musicaiap.ui.player.PlayerViewModel
import com.example.musicaiap.service.toMediaItems

/**
 * 播放列表屏幕
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PlaylistScreen(
    playlistId: String,
    viewModel: PlaylistViewModel = hiltViewModel(),
    playerViewModel: PlayerViewModel = hiltViewModel(),
    onBackClick: () -> Unit = {},
    onPlayerClick: () -> Unit = {},
    navigationState: NavigationState
) {
    val snackbarHostState = remember { SnackbarHostState() }
    val scrollState = rememberLazyListState()
    var headerAlpha by remember { mutableStateOf(1f) }
    
    // 添加播放列表底部弹窗显示状态控制
    var isPlaylistBottomSheetVisible by remember { mutableStateOf(false) }
    
    // 获取PlayerController
    val playerController = playerViewModel.playerController
    
    // 获取当前播放列表
    val currentPlaylist by playerController.playerState.collectAsState()
    
    val uiState by viewModel.CollectState { effect ->
        when (effect) {
            is PlaylistContract.Effect.NavigateToPlayer -> {
                onPlayerClick()
            }
            is PlaylistContract.Effect.ShowToast -> {
                snackbarHostState.showSnackbar(effect.message)
            }
            is PlaylistContract.Effect.NavigateBack -> {
                onBackClick()
            }
        }
    }
    
    // 发送加载播放列表意图
    LaunchedEffect(key1 = playlistId) {
        viewModel.sendIntent(PlaylistContract.Intent.LoadPlaylist(playlistId))
    }
    
    // 添加播放列表底部弹窗
    PlaylistBottomSheet(
        isVisible = isPlaylistBottomSheetVisible,
        onDismiss = { isPlaylistBottomSheetVisible = false },
        playQueue = currentPlaylist.currentPlaylist ?: emptyList(),
        currentSong = uiState.currentPlayingSong,
        onSongClick = { song ->
            viewModel.sendIntent(PlaylistContract.Intent.ClickSong(song))
            isPlaylistBottomSheetVisible = false
        }
    )
    
    Scaffold(
        snackbarHost = { SnackbarHost(hostState = snackbarHostState) },
        topBar = {
            TopAppBar(
                title = { 
                    if (scrollState.firstVisibleItemIndex > 0) {
                        Text(uiState.playlist?.name ?: "歌单") 
                    } else {
                        Text("")
                    }
                },
                navigationIcon = {
                    IconButton(onClick = onBackClick) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                },
                actions = {
                    IconButton(onClick = { /* TODO */ }) {
                        Icon(
                            imageVector = Icons.Default.MoreVert,
                            contentDescription = "更多选项"
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = if (scrollState.firstVisibleItemIndex > 0) 
                                    MaterialTheme.colorScheme.surface 
                                    else Color.Transparent
                )
            )
        },
        bottomBar = {
            // Mini播放器
            MiniPlayer(
                isVisible = uiState.currentPlayingSong != null,
                currentSong = uiState.currentPlayingSong,
                isPlaying = uiState.isPlaying,
                progress = if (uiState.duration > 0) {
                    uiState.currentPosition.toFloat() / uiState.duration
                } else {
                    0f
                },
                currentPosition = uiState.currentPosition,
                duration = uiState.duration,
                onPlayPause = { 
                    viewModel.sendIntent(PlaylistContract.Intent.TogglePlayPause) 
                },
                onSkipNext = { 
                    viewModel.sendIntent(PlaylistContract.Intent.NextSong) 
                },
                onSkipPrevious = {
                    viewModel.sendIntent(PlaylistContract.Intent.PreviousSong)
                },
                onSeek = { progress ->
                    if (uiState.duration > 0) {
                        val seekPosition = (progress * uiState.duration).toLong()
                        viewModel.sendIntent(PlaylistContract.Intent.SeekTo(seekPosition))
                    }
                },
                onPlayerClick = onPlayerClick,
                onPlaylistClick = { isPlaylistBottomSheetVisible = true },
                isInPlaylistScreen = navigationState.isInPlaylistScreen
            )
        }
    ) { paddingValues ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .background(MaterialTheme.colorScheme.background)
        ) {
            if (uiState.isLoading) {
                CircularProgressIndicator(
                    modifier = Modifier.align(Alignment.Center),
                    color = QQGreen
                )
            } else if (uiState.error != null) {
                Text(
                    text = uiState.error ?: "未知错误",
                    color = MaterialTheme.colorScheme.error,
                    modifier = Modifier
                        .align(Alignment.Center)
                        .padding(16.dp)
                )
            } else {
                QQMusicPlaylistContent(
                    playlist = uiState.playlist,
                    songs = uiState.songs,
                    currentSong = uiState.currentPlayingSong,
                    isPlaying = uiState.isPlaying,
                    scrollState = scrollState,
                    onSongClick = { song ->
                        viewModel.sendIntent(PlaylistContract.Intent.ClickSong(song))
                    },
                    onPlayAllClick = {
                        if (uiState.songs.isNotEmpty()) {
                            viewModel.sendIntent(PlaylistContract.Intent.PlayAll)
                        }
                    },
                    onFavoriteClick = { /* TODO */ }
                )
            }
        }
    }
}

@Composable
private fun QQMusicPlaylistContent(
    playlist: Playlist?,
    songs: List<Song>,
    currentSong: Song?,
    isPlaying: Boolean,
    scrollState: androidx.compose.foundation.lazy.LazyListState,
    onSongClick: (Song) -> Unit,
    onPlayAllClick: () -> Unit,
    onFavoriteClick: () -> Unit
) {
    LazyColumn(
        state = scrollState,
        modifier = Modifier
            .fillMaxSize()
            .background(QQPlaylistBackground)
    ) {
        // 头部封面和信息
        item {
            PlaylistHeader(
                playlist = playlist,
                onPlayAllClick = onPlayAllClick,
                onFavoriteClick = onFavoriteClick
            )
        }
        
        // VIP提示
        item {
            VipInfoSection()
        }
        
        // 播放控制
        item {
            PlayControlSection(
                songCount = songs.size,
                onPlayAllClick = onPlayAllClick
            )
        }
        
        // 歌曲列表
        itemsIndexed(songs) { index, song ->
            SongItem(
                song = song,
                index = index + 1,
                isCurrentSong = currentSong?.id == song.id,
                isPlaying = isPlaying && currentSong?.id == song.id,
                onClick = { onSongClick(song) }
            )
            
            if (index < songs.size - 1) {
                HorizontalDivider(
                    modifier = Modifier.padding(start = 72.dp),
                    color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.2f),
                    thickness = 0.5.dp
                )
            }
        }
        
        // 底部空间
        item {
            Spacer(modifier = Modifier.height(80.dp))
        }
    }
}

@Composable
private fun PlaylistHeader(
    playlist: Playlist?,
    onPlayAllClick: () -> Unit,
    onFavoriteClick: () -> Unit
) {
    if (playlist == null) return
    
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(340.dp)
    ) {
        // 模糊背景
        AsyncImage(
            model = ImageRequest.Builder(LocalContext.current)
                .data(playlist.coverUrl)
                .crossfade(true)
                .build(),
            contentDescription = null,
            contentScale = ContentScale.Crop,
            modifier = Modifier
                .fillMaxSize()
                .blur(20.dp)
                .alpha(0.5f)
        )
        
        // 渐变遮罩
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(
                    QQPlaylistBackground.copy(alpha = 0.85f)
                )
        )
        
        // 内容
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 80.dp) // 为顶部状态栏和标题栏留出空间
                .padding(horizontal = 16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 封面图
            Card(
                shape = RoundedCornerShape(12.dp),
                modifier = Modifier
                    .size(160.dp)
            ) {
                Box {
                    AsyncImage(
                        model = ImageRequest.Builder(LocalContext.current)
                            .data(playlist.coverUrl)
                            .crossfade(true)
                            .build(),
                        contentDescription = playlist.name,
                        contentScale = ContentScale.Crop,
                        modifier = Modifier.fillMaxSize()
                    )
                    
                    // AI标签
                    if (playlist.name.startsWith("每日") || playlist.name.startsWith("为你推荐")) {
                        Box(
                            modifier = Modifier
                                .padding(8.dp)
                                .clip(RoundedCornerShape(4.dp))
                                .background(QQTagBackground)
                                .padding(horizontal = 6.dp, vertical = 2.dp)
                                .align(Alignment.TopStart)
                        ) {
                            Text(
                                text = "AI歌单",
                                color = QQGreen,
                                fontSize = 10.sp
                            )
                        }
                    }
                }
            }
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 歌单标题
            Text(
                text = playlist.name,
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.Bold,
                textAlign = TextAlign.Center,
                color = MaterialTheme.colorScheme.onBackground
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 更新信息
            val dateFormat = SimpleDateFormat("yyyy.MM.dd", Locale.getDefault())
            val updateDate = dateFormat.format(Date())
            
            Text(
                text = "更新于 $updateDate | 歌曲 ${playlist.songCount ?: 0}首",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f)
            )
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 操作按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                // 收藏按钮
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    modifier = Modifier.clickable(onClick = onFavoriteClick)
                ) {
                    Icon(
                        imageVector = Icons.Outlined.FavoriteBorder,
                        contentDescription = "收藏",
                        tint = MaterialTheme.colorScheme.onBackground,
                        modifier = Modifier.size(24.dp)
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = "收藏",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onBackground
                    )
                }
                
                // 评论按钮
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    modifier = Modifier.clickable { /* TODO */ }
                ) {
                    Text(
                        text = "${(100..999).random()}",
                        style = MaterialTheme.typography.titleMedium,
                        color = MaterialTheme.colorScheme.onBackground
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = "评论",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onBackground
                    )
                }
                
                // 分享按钮
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    modifier = Modifier.clickable { /* TODO */ }
                ) {
                    Icon(
                        imageVector = Icons.Default.Share,
                        contentDescription = "分享",
                        tint = MaterialTheme.colorScheme.onBackground,
                        modifier = Modifier.size(24.dp)
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = "分享",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onBackground
                    )
                }
                
                // 更多按钮
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    modifier = Modifier.clickable { /* TODO */ }
                ) {
                    Icon(
                        imageVector = Icons.Outlined.MoreVert,
                        contentDescription = "更多",
                        tint = MaterialTheme.colorScheme.onBackground,
                        modifier = Modifier.size(24.dp)
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = "更多",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onBackground
                    )
                }
            }
        }
    }
}

@Composable
private fun VipInfoSection() {
    Surface(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp),
        shape = RoundedCornerShape(12.dp),
        color = QQVipBackground
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = "开通VIP畅享千万曲库",
                    style = MaterialTheme.typography.bodyMedium,
                    fontWeight = FontWeight.Bold,
                    color = QQVipText
                )
                
                Spacer(modifier = Modifier.height(4.dp))
                
                Text(
                    text = "海量音乐无限下载",
                    style = MaterialTheme.typography.bodySmall,
                    color = QQVipText.copy(alpha = 0.8f)
                )
            }
            
            Box(
                modifier = Modifier
                    .clip(RoundedCornerShape(16.dp))
                    .background(QQGreen)
                    .padding(horizontal = 12.dp, vertical = 6.dp)
            ) {
                Text(
                    text = "立即开通",
                    style = MaterialTheme.typography.bodySmall,
                    color = Color.White
                )
            }
        }
    }
}

@Composable
private fun PlayControlSection(
    songCount: Int,
    onPlayAllClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 播放全部按钮
        Row(
            modifier = Modifier
                .weight(1f)
                .clickable(onClick = onPlayAllClick),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Box(
                modifier = Modifier
                    .size(32.dp)
                    .clip(CircleShape)
                    .background(QQGreen),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    imageVector = Icons.Default.PlayArrow,
                    contentDescription = "播放全部",
                    tint = Color.White,
                    modifier = Modifier.size(20.dp)
                )
            }
            
            Spacer(modifier = Modifier.width(8.dp))
            
            Column {
                Text(
                    text = "播放全部",
                    style = MaterialTheme.typography.bodyMedium,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.onBackground
                )
                
                Text(
                    text = "共${songCount}首",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f)
                )
            }
        }
        
        // 多选按钮
        Box(
            modifier = Modifier
                .clip(RoundedCornerShape(16.dp))
                .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f))
                .padding(horizontal = 12.dp, vertical = 6.dp)
                .clickable { /* TODO */ }
        ) {
            Text(
                text = "多选",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onBackground
            )
        }
        
        Spacer(modifier = Modifier.width(8.dp))
        
        // 下载全部按钮
        Box(
            modifier = Modifier
                .clip(RoundedCornerShape(16.dp))
                .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f))
                .padding(horizontal = 12.dp, vertical = 6.dp)
                .clickable { /* TODO */ }
        ) {
            Text(
                text = "下载全部",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onBackground
            )
        }
    }
}

@Composable
private fun SongItem(
    song: Song,
    index: Int,
    isCurrentSong: Boolean,
    isPlaying: Boolean,
    onClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .padding(vertical = 8.dp, horizontal = 16.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 歌曲序号
        Text(
            text = index.toString(),
            style = MaterialTheme.typography.bodyLarge,
            color = if (isCurrentSong) QQGreen else MaterialTheme.colorScheme.onBackground.copy(alpha = 0.6f),
            modifier = Modifier.width(24.dp),
            textAlign = TextAlign.Center
        )
        
        Spacer(modifier = Modifier.width(16.dp))
        
        // 歌曲信息
        Column(
            modifier = Modifier.weight(1f)
        ) {
            // 歌曲标题
            if (isCurrentSong) {
                Text(
                    text = buildAnnotatedString {
                        withStyle(SpanStyle(color = QQGreen)) {
                            append(song.title)
                        }
                    },
                    style = MaterialTheme.typography.bodyLarge,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            } else {
                Text(
                    text = song.title,
                    style = MaterialTheme.typography.bodyLarge,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    color = MaterialTheme.colorScheme.onBackground
                )
            }
            
            Spacer(modifier = Modifier.height(4.dp))
            
            // 艺术家和来源
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                if (song.isVip) {
                    Box(
                        modifier = Modifier
                            .padding(end = 4.dp)
                            .clip(RoundedCornerShape(2.dp))
                            .background(QQVipText)
                            .padding(horizontal = 3.dp, vertical = 1.dp)
                    ) {
                        Text(
                            text = "VIP",
                            fontSize = 9.sp,
                            color = Color.White
                        )
                    }
                }
                
        Text(
                    text = "${song.artist}",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.6f),
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }
        
        // 右侧图标
        IconButton(
            onClick = { /* TODO */ },
            modifier = Modifier.size(32.dp)
        ) {
            Icon(
                imageVector = Icons.Outlined.MoreVert,
                contentDescription = "更多选项",
                tint = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.6f),
                modifier = Modifier.size(16.dp)
            )
        }
    }
    
    // 显示播放进度条（如果是当前播放的歌曲）
    if (isCurrentSong) {
        LinearProgressIndicator(
            progress = { 0.3f }, // 使用实际的播放进度
            modifier = Modifier
                .fillMaxWidth()
                .height(1.dp)
                .padding(horizontal = 16.dp),
            color = QQGreen,
            trackColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f)
        )
    }
}

@Preview(showBackground = true)
@Composable
private fun PlaylistScreenPreview() {
    val navState = remember { NavigationState() }
    PlaylistScreen(
        playlistId = "1",
        navigationState = navState
    )
} 